let { userList, personList } = require("./mock");
const bodyParser = require("body-parser");
const JWT = require("jsonwebtoken");
const key = "qwhbqwqw";
module.exports = (app) => {
  app.use(bodyParser.json());

  // 登录
  app.post("/api/login", (req, res) => {
    const { username, password } = req.body;
    const result = userList.find((v) => {
      return v.username === username && v.password === password;
    });

    if (result) {
      res.send({
        code: 200,
        message: "登录成功",
        data: {
          nickname: result.nickname,
          avator: result.avator,
          token: JWT.sign(
            {
              nickname: result.nickname,
              avator: result.avator,
              username: result.username,
            },
            key
          ),
        },
      });
    } else {
      res.send({
        message: "账户密码错误",
        code: 403,
      });
    }
  });
  // 审核列表添加接口
  app.post("/api/person/verify", (req, res) => {
    const { name, sex, tel, age, address } = req.body;
    const item = {
      name,
      sex,
      tel,
      age,
      address,
      id: Math.random().toString().slice(2),
      isVerify: false,
    };
    personList.unshift(item);
    res.send({
      code: 200,
      message: "数据添加成功！！",
    });
  });
  // 人员列表修改接口
  app.post("/api/person/list/:id", (req, res) => {
    const { id } = req.params;
    const item = personList.find((v) => v.id === id);
    Object.assign(item, req.body);
    res.send({
      code: 200,
      message: "修改成功",
    });
  });

  // 审核列表
  app.get("/api/person/verifys", (req, res) => {
    const { value } = req.query;
    const result = personList.filter((v) => {
      return (
        v.isVerify === false &&
        (v.name.includes(value) ||
          v.id.includes(value) ||
          v.address.includes(value) ||
          v.tel.includes(value))
      );
    });
    res.send({
      code: 200,
      data: result,
    });
  });
  // 审核列表审核接口
  app.get("/api/person/verify/:id", (req, res) => {
    const { id } = req.params;
    let item = null;
    personList = personList.filter((v) => {
      if (v.id === id) {
        item = { ...v };
      }

      return v.id !== id;
    });
    item.isVerify = true;

    personList.unshift(item);

    res.send({
      code: 200,
      message: "审核通过！！",
    });
  });

  // 人员列表
  app.get("/api/person/list", (req, res) => {
    const result = personList.filter((v) => v.isVerify);
    res.send({
      code: 200,
      data: result,
    });
  });
};
